package com.xiaoda.controller;

import com.xiaoda.entity.*;
import com.xiaoda.service.ArticleService;
import com.xiaoda.service.CommentService;
import com.xiaoda.service.LikeService;
import com.xiaoda.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 */

@Controller
@CrossOrigin
@RequestMapping("/user")
@ResponseBody
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    LikeService likeService;

    @Autowired
    ArticleService articleService;

    @Autowired
    CommentService commentService;

    /**
     * 用户 登录 || 注册
     *
     * @param account  账号
     * @param password 密码
     * @param checked  记住密码
     * @return 返回 登录 || 注册 结果
     */
    @GetMapping("/login")
    public JsonResult Login(@RequestParam("account") String account,
                            @RequestParam("password") String password,
                            @RequestParam("checked") boolean checked) {
        JsonResult json = new JsonResult();
        User user = new User();
        User user1 = userService.findById(account);
        if (user1 == null) {
            user.setAccount(account);
            user.setPassword(password);
            int row = userService.addUser(user);
            if (row <= 0) {
                json.setCode(404);
                json.setMsg("用户注册失败！！！");
                user = new User();
            } else {
                json.setCode(200);
                json.setMsg("用户注册成功！！！");
                user.setPassword(checked ? password : null);
            }
            json.setData(user);
        } else {
            user = userService.userLogin(account, password);
            if (user == null) {
                json.setCode(404);
                json.setMsg("用户密码输入错误，请检查后再试！！！");
            } else {
                json.setCode(200);
                json.setMsg("用户登录成功！！！");
                user.setPassword(checked ? password : null);
            }
            json.setData(user);
        }
        return json;
    }

    /**
     * 查询用户数据
     *
     * @param ownAccount   当前用户账号
     * @param otherAccount 其他用户账号
     * @return 返回用户数据
     */
    @GetMapping("/info")
    public JsonResult info(@RequestParam("ownAccount") String ownAccount,
                           @RequestParam("otherAccount") String otherAccount) {
        JsonResult json = new JsonResult();
        User user = userService.findById(otherAccount);
        if (user == null) {
            json.setCode(404);
            json.setMsg("用户不存在！！！");
        } else {
            json.setCode(200);
            json.setMsg("用户数据查询成功！！！");
            if (!ownAccount.equals(otherAccount)) {
                user.setPassword(null);
            }
        }
        json.setData(user);
        return json;
    }

    /**
     * 查询用户关注列表
     *
     * @param ownAccount   当前用户账号
     * @param otherAccount 目标用户账号
     * @param start        开始位置
     * @param end          结束位置
     * @return 返回用户关注列表
     */
    @GetMapping("/follow")
    public JsonResult follow(@RequestParam("ownAccount") String ownAccount,
                             @RequestParam("otherAccount") String otherAccount,
                             @RequestParam("start") int start,
                             @RequestParam("end") int end) {
        JsonResult json = new JsonResult();
        List<Like> likeList = likeService.findAllFollowed(otherAccount, start, end);
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Like like : likeList) {
            Map<String, Object> map = new HashMap<>();
            if (like.getFromUid().getAccount().equals(otherAccount)) {
                map = this.jsonChangeMap(ownAccount, like.getToUid());
                map.put("whoConcern", "own");
            }
            if (like.getToUid().getAccount().equals(otherAccount)) {
                map = this.jsonChangeMap(ownAccount, like.getFromUid());
                map.put("whoConcern", "other");
            }
            mapList.add(map);
        }

        for (int i = 0; i < mapList.size(); i++) {
            for (int j = 0; j < mapList.size(); j++) {
                if (i != j && mapList.get(i).get("account").equals(mapList.get(j).get("account"))) {
                    mapList.get(i).put("whoConcern", "both");
                    mapList.remove(mapList.get(j));
                }
            }
        }

        if (mapList.isEmpty()) {
            json.setCode(404);
            json.setMsg("关注列表为空！！！");
        } else {
            json.setCode(200);
            json.setMsg("关注列表查询成功！！！");
        }
        json.setData(mapList);
        return json;
    }

    /**
     * 修改用户信息
     *
     * @param user 用户信息
     * @return 返回修改结果
     */
    @PutMapping("/update")
    public JsonResult update(@RequestBody User user) {
        JsonResult json = new JsonResult();
        if (!"".equals(user.getAvatar())) {
            user.setAvatar("images/" + user.getAvatar());
        }
        int row = userService.updateUser(user);
        if (row > 0) {
            json.setCode(200);
            json.setMsg("用户信息修改成功！！！");
        } else {
            json.setCode(404);
            json.setMsg("用户信息修改失败！！！");
        }
        json.setData(null);
        return json;
    }

    /**
     * 查询用户消息
     *
     * @param ownAccount   当前用户账号
     * @param otherAccount 目标用户账号
     * @return 返回用户消息
     */
    @GetMapping("/message")
    public JsonResult message(@RequestParam("ownAccount") String ownAccount,
                              @RequestParam("otherAccount") String otherAccount) {
        JsonResult json = new JsonResult();
        User user = userService.findById(otherAccount);
        Map<String, Object> map = new HashMap<>();
        if (user != null) {
            json.setCode(200);
            json.setMsg("用户数据查询成功！！！");
            map = this.jsonChangeMap(ownAccount, user);
            map.put("isOwn", ownAccount.equals(otherAccount));
        } else {
            json.setCode(404);
            json.setMsg("用户不存在！！！");
        }
        json.setData(map);
        return json;
    }

    /**
     * 根据关键字获取用户数据
     *
     * @param map 关键字
     * @return 返回用户数据
     */
    @PostMapping("/keyword")
    public JsonResult keyword(@RequestBody Map<String, Object> map) throws UnsupportedEncodingException {
        JsonResult json = new JsonResult();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof String) {
                String decodeValue = URLDecoder.decode((String) value, "UTF-8");
                entry.setValue(decodeValue);
            }
        }
        List<User> list = userService.findAllByKeyword(map);
        if (list.isEmpty()) {
            json.setCode(404);
            json.setMsg("未查询到用户数据！！！");
        } else {
            json.setCode(200);
            json.setMsg("成功查询到用户数据！！！");
        }
        json.setData(list);
        return json;
    }

    /**
     * 删除用户
     *
     * @param account 用户账号
     * @return 返回删除结果
     */
    @DeleteMapping("/delete/{account}")
    public JsonResult delete(@PathVariable("account") String account) {
        JsonResult json = new JsonResult();
        int row = userService.deleteByAccount(account);
        if (row > 0) {
            json.setCode(200);
            json.setMsg("用户删除成功！！！");
        } else {
            json.setCode(404);
            json.setMsg("用户删除失败！！！");
        }
        json.setData(null);
        return json;
    }

    /**
     * 添加用户
     *
     * @param user 用户信息
     * @return 返回添加结果
     */
    @PostMapping("/add")
    public JsonResult add(@RequestBody User user) {
        JsonResult json = new JsonResult();
        User u = userService.findById(user.getAccount());
        if (u != null) {
            json.setCode(404);
            json.setMsg("用户已存在！！！");
        } else {
            int row = userService.addFullUser(user);
            if (row > 0) {
                json.setCode(200);
                json.setMsg("用户添加成功！！！");
            } else {
                json.setCode(404);
                json.setMsg("用户添加失败！！！");
            }
        }
        json.setData(null);
        return json;
    }

    /**
     * 处理用户列表
     *
     * @param account 当前用户账号
     * @param u       用户信息
     * @return 返回处理后的用户信息
     */
    public Map<String, Object> jsonChangeMap(String account, User u) {
        Map<String, Object> map = new HashMap<>();
        map.put("account", u.getAccount());
        map.put("nickname", u.getNickname());
        map.put("avatar", u.getAvatar());
        map.put("gender", u.getGender());
        map.put("commentNum", commentService.countCommentNum(u.getAccount()));
        map.put("articleNum", articleService.countArticleNum(u.getAccount()));
        map.put("likeNum", likeService.countLikeNum(u.getAccount()));
        map.put("hasConcern", likeService.findByUid(account, u.getAccount()) != null);
        return map;
    }

}
